********************************************************************************
** 	TITLE:		at2013_polls		                                          ** 	
**	AUTHOR:	    Philippe Mongrain                                             **
**	DATE:		October 2022 					                              **	
**  VERSION:	Stata 16					                                  **	
********************************************************************************

* Version control

version 16.0

* Import data

import excel surveys, firstrow sheet(at2013) clear
destring _all, replace

* Generate survey date

format %tdMon_DD,_CCYY polldate

* Generate election date

gen edate = 20130929

gen electiondate = date(string(edate,"%8.0f"),"YMD")

format %tdMon_DD,_CCYY electiondate

* Time of survey

gen time = (electiondate - polldate) + 1

* Generate mean vote intention value by day

bysort time : egen spovote = mean(spo)
bysort time : egen ovpvote = mean(ovp)
bysort time : egen fpovote = mean(fpo)
bysort time : egen grunevote = mean(grune)
bysort time : egen stronachvote = mean(stronach)
bysort time : egen bzovote = mean(bzo)
bysort time : egen neosvote = mean(neos)
bysort time : egen piratenvote = mean(piraten)
bysort time : egen kpovote = mean(kpo)
bysort time : egen othersvote = mean(others)

sort time

* Drop duplicates

duplicates tag polldate, gen(dup)
duplicates drop polldate, force
drop dup

* Reshape the dataset

rename spo v_spo
rename ovp v_ovp
rename fpo v_fpo
rename grune v_grune
rename stronach v_stronach
rename bzo v_bzo
rename neos v_neos
rename piraten v_piraten
rename kpo v_kpo
rename others v_others

reshape long v_, i(polldate) j(party) string

rename v_ vote

keep polldate electiondate party vote poll time

order poll polldate electiondate time party vote

* Generate rank of parties

gsort polldate -vote

bysort polldate : gen rank = _n

gen first = party if rank == 1
gen second = party if rank == 2
gen third = party if rank == 3

bysort polldate : gen winner = first[1]
bysort polldate : gen runnerup = second[2]
bysort polldate : gen thirdplace = third[3]

* Generate poll margin

bysort polldate : gen pollmar = vote[1] - vote[2]

* Drop duplicates

duplicates tag polldate, gen(dup)
duplicates drop polldate, force
drop dup

* Misleading poll

gen misleading = 0 if winner == "spo" & pollmar >= 1
replace misleading = 1 if misleading!=0

* Save

drop if time == 0 | time == .

keep polldate pollmar misleading time

save "at2013_polls.dta", replace